<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use think\Request;
use think\facade\Db;
use think\facade\View;
use \liliuwei\think\Jump;

class Student extends BaseController
{
	use Jump;
	/**
	 * 显示资源列表
	 *
	 * @return \think\Response
	 */
	public function index()
	{
		//
		$studentList = Db::name("student")->order("id","desc")->paginate(5);
		View::assign("studentlist",$studentList);

		return View::fetch('list');

	}

	/**
	 * 显示创建资源表单页.
	 *
	 * @return \think\Response
	 */
	public function create()
	{
		View::assign("sname","zhangshilong");
		return View::fetch('create');

	}

	/**
	 * 保存新建的资源
	 *
	 * @param  \think\Request $request
	 *
	 * @return \think\Response
	 */
	public function save(Request $request)
	{

		if(empty($request->post("username"))) {
			$this->error("用户名不能为空",'/student/create');
		}

		$saveData = ["username" => $request->post("username"),
		             "email"    => $request->post("email"),
		             "mobile"   => $request->post("mobile"),
					"id"   => $request->post("id")
		];



		//图片上传
		$file = $request->file("img");
		if($file) {
			$image = \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
			$saveData["img"] = "/storage/".$image;
		}

		if(Db::name("student")->save($saveData)) {
			return $this->success("保存成功","/student/index");
		}
	}

	/**
	 * 显示指定的资源
	 *
	 * @param  int $id
	 *
	 * @return \think\Response
	 */
	public function read($id)
	{
		//
	}

	/**
	 * 显示编辑资源表单页.
	 *
	 * @param  int $id
	 *
	 * @return \think\Response
	 */
	public function edit($id)
	{
		$detail = Db::table('student')->where('id', $id)->find();
		View::assign("detail",$detail);
		return View::fetch('edit');
	}

	/**
	 * 保存更新的资源
	 *
	 * @param  \think\Request $request
	 * @param  int            $id
	 *
	 * @return \think\Response
	 */
	public function update(Request $request)
	{
		//

		if(empty($request->post("username"))) {
			$this->error("用户名不能为空",'/student/edit/'.$request->post("id"));
		}

		$saveData = ["username" => $request->post("username"),
		             "email"    => $request->post("email"),
		             "mobile"   => $request->post("mobile")
		];



		//图片上传
		if(!empty($_FILES["img"]["name"])) {
			$file = $request->file("img");
			$image = \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
			$saveData["img"] = "/storage/".$image;
		}

		if(Db::name("student")->where("id",$request->post("id"))->update($saveData)) {
			return $this->success("保存成功","/student/index");
		} else {
			return $this->success("保存失败","/student/index");
		}
	}

	/**
	 * 删除指定资源
	 *
	 * @param  int $id
	 *
	 * @return \think\Response
	 */
	public function delete($id)
	{
		if(!isset($id) || empty($id)) {
			$this->error("id不能为空","/student/index");
		}
		if(Db::name("student")->delete($id)) {
			$this->success("删除成功","/student/index");
		} else {
			$this->success("删除失败","/student/index");
		}
	}
}
